package org.javaymw.springboot.queue;

import org.javaymw.springboot.dto.sys.SLogDto;
import org.javaymw.springboot.entity.sys.SLogEntity;
import org.javaymw.springboot.service.SLogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * 描述：启动消费操作日志队列的线程
 * <p>
 * Author: 赵新国
 * Date: 2017/12/13 15:16
 */
@Component
public class ConsumeSLogQueue {

    @Autowired
    private SLogService sLogService;

    /**
     * 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行，并且只会被服务器调用一次，
     * 类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后，init()方法之前运行
     */
    @PostConstruct
    public void startThread() {
        // 初始化2个大小的固定线程池
        ThreadPoolExecutor executor  = new ThreadPoolExecutor(1, 2,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        executor.submit(new PollSLog(sLogService));
        executor.submit(new PollSLog(sLogService));
    }

    class PollSLog implements Runnable {

        SLogService sLogService;

        public PollSLog(SLogService sLogService) {
            this.sLogService = sLogService;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    SLogEntity sLogEntity = SLogQueue.getInstance().poll();
                    if(sLogEntity != null){
                        SLogDto sLogDto = new SLogDto();
                        BeanUtils.copyProperties(sLogEntity, sLogDto);
                        sLogService.saveSLog(sLogDto);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
